package com.example.wangzh.developkit.utils;

import android.os.Build;
import android.os.Environment;
import android.os.FileUtils;

import com.example.wangzh.developkit.constant.LogTag;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ThreadPoolExecutor;

import leakcanary.DefaultOnHeapAnalyzedListener;
import leakcanary.OnHeapAnalyzedListener;
import shark.HeapAnalysis;

public class upLoadListener implements OnHeapAnalyzedListener {
    OnHeapAnalyzedListener defaultOnHeapAnalyzedListener =
            DefaultOnHeapAnalyzedListener.Companion.create();
    private static final String saveDirPath = Environment.getExternalStorageDirectory() +
            File.separator + "decelopkit_leakCanary" + File.separator;

    @Override
    public void onHeapAnalyzed(@NotNull final HeapAnalysis heapAnalysis) {
        final File saveDir = new File(saveDirPath);
        if (!saveDir.exists()) {
            saveDir.mkdirs();
        }
        ThreadPoolFactory.getFactory().getDefaultThreadPool().execute(new Runnable() {
            @Override
            public void run() {
                try {
                    File descriptionDest = new File(saveDirPath + "leak" +
                            new SimpleDateFormat("yyyy-MM-dd_HHmmss").format(new Date()) +
                            ".txt");
                    FileUtil.writeStringToFile(descriptionDest.getPath(), heapAnalysis.toString());
                    File source = heapAnalysis.getHeapDumpFile();
                    File dest = new File(saveDirPath + source.getName());
                    FileUtil.copyFile(source.getPath(), dest.getPath());
                } catch (IOException e) {
                    LogUtils.i(LogTag.LEAK_CANARY, "复制canary文件失败");
                    LogUtils.logThrowable(LogTag.LEAK_CANARY, e);
                    e.printStackTrace();
                }
            }
        });
        defaultOnHeapAnalyzedListener.onHeapAnalyzed(heapAnalysis);
    }
}
